package com.jplus.mvc.action.api.third;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import com.jplus.core.anno.boot.Component;
import com.jplus.core.anno.com.Value;
import com.jplus.core.plugin.async.Async;
import com.jplus.core.plugin.scheduling.Scheduled;
import com.jplus.core.utill.HttpClientUtil;
import com.jplus.core.utill.JSON;
import com.jplus.core.utill.JSON.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class BaiduApi {
	private Logger log = LoggerFactory.getLogger(BaiduApi.class);
	private HttpClientUtil http = new HttpClientUtil();

	// 百度AI
	public @Value("${BAIDU.APP_ID}") String BAIDU_APP_ID;
	public @Value("${BAIDU.API_KEY}") String BAIDU_API_KEY;
	public @Value("${BAIDU.SECRET_KEY}") String BAIDU_SECRET_KEY;

	private String access_token;

	@PostConstruct
	@Async("fixedThreadPool")
	@Scheduled(cron = "0 0 6 * * ?")
	public void init() {
		log.info("[init]>> load baidu api access_token");
		String tokenUri = "https://aip.baidubce.com/oauth/2.0/token";
		Map<String, Object> param = new HashMap<>();
		param.put("grant_type", "client_credentials");
		param.put("client_id", BAIDU_API_KEY);
		param.put("client_secret", BAIDU_SECRET_KEY);
		JSONObject jobj = JSON.parseObject(http.doGet(tokenUri, param));
		this.access_token = jobj.getString("access_token");
		log.info("\t baidu access_token：" + access_token);
	}

	/**
	 * 身份证ocr <br>
	 * https://ai.baidu.com/docs#/OCR-API-Idcard/top
	 */
	public JSONObject idcardOCR(String image, Boolean cardSide) {
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + access_token;
		HashMap<String, Object> param = new HashMap<>();
		param.put("detect_direction", "true");
		param.put("id_card_side", cardSide ? "front" : "back");
		param.put("image", image);
		JSONObject jobj = JSON.parseObject(http.doPost(url, param));
		log.debug(jobj.toString());
		return jobj;
	}

	/**
	 * 银行卡ocr<br>
	 * https://ai.baidu.com/docs#/OCR-API-Bankcard/top
	 */
	public JSONObject bankcardOCR(String image) {
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard?access_token=" + access_token;
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("image", image);
		JSONObject jobj = JSON.parseObject(http.doPost(url, param));
		log.debug(jobj.toString());
		return jobj;
	}

	// /**
	// * 实名认证二要素 企业账号500次
	// */
	// public boolean idCardAuth(String cardNo, String realName) {
	// String url =
	// "https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch?access_token=" +
	// access_token;
	// HashMap<String, Object> param = new HashMap<String, Object>();
	// param.put("id_card_number", cardNo);
	// param.put("name", realName);
	// JSONObject jobj = JSON.parseObject(http.doPost(url, param));
	// log.info(jobj.toString());
	// return jobj.getInt("error_code") == 0;
	// }

}
